package conn

import (
	"context"

	"gitee.com/ander888/tools/model"
	"gitee.com/ander888/tools/zlog"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/minio/minio-go/v7/pkg/lifecycle"
)

type MinioClient struct {
	Conf model.MinioConf
	Conn *minio.Client
	Err  error
}

func (mn *MinioClient) NewMinioClient() {
	mn.Conn, mn.Err = minio.New(mn.Conf.Endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(mn.Conf.AccessKeyID, mn.Conf.SecretAccessKey, ""),
		Secure: mn.Conf.UseSSL,
	})
}

func (mn *MinioClient) SetBucketLifecycle(bucketName string, expirationDays int) {
	ctx := context.Background()
	config := lifecycle.NewConfiguration()
	// 应用更新后的生命周期规则到存储桶
	config.Rules = []lifecycle.Rule{
		{
			ID:     "expire-bucket-" + bucketName,
			Status: "Enabled",
			Expiration: lifecycle.Expiration{
				Days: lifecycle.ExpirationDays(expirationDays),
			},
		},
	}
	err := mn.Conn.SetBucketLifecycle(ctx, bucketName, config)
	if err != nil {
		zlog.Err(err, "设置桶的生命周期失败")
		return
	}
}
